package com.cinc.mdm.modules.sequence.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinc.mdm.modules.sequence.entity.MdmSequence;
import com.cinc.mdm.modules.sequence.mapper.MdmSequenceMapper;
import com.cinc.mdm.modules.sequence.service.IMdmSequenceService;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: 自增序列
 * @Author: jeecg-boot
 * @Date: 2023-08-31
 * @Version: V1.0
 */
@Slf4j
@Service
public class MdmSequenceServiceImpl extends ServiceImpl<MdmSequenceMapper, MdmSequence> implements IMdmSequenceService {

    @Autowired
    private MdmSequenceMapper mdmSequenceMapper;

    @Transactional
    @Override
    public int nextSeqNo(String seqType, String seqVal) {
        if (oConvertUtils.isEmpty(seqType)) {
            throw new RuntimeException("自增序列号获取失败，序列类型不能为空");
        }
        seqVal = oConvertUtils.isEmpty(seqVal) ? "-" : seqVal;
        int nextVal = 0;
        LambdaQueryWrapper<MdmSequence> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MdmSequence::getSeqType, seqType);
        queryWrapper.eq(MdmSequence::getSeqVal, seqVal);
        MdmSequence data = baseMapper.selectOne(queryWrapper);
        if (data == null) {
            MdmSequence add = new MdmSequence();
            add.setId(UUIDGenerator.generate());
            add.setSeqType(seqType);
            add.setSeqVal(seqVal);
            add.setSeqNo(1);
            baseMapper.insert(add);
            nextVal = 1;
        } else {
            mdmSequenceMapper.increaseSeqNo(seqType, seqVal);
            data = baseMapper.selectOne(queryWrapper);
            nextVal = data.getSeqNo();
        }

        return nextVal;
    }

    @Transactional
    @Override
    public int resetSeqNo(String seqType, String seqVal) {
        if (oConvertUtils.isEmpty(seqType)) {
            throw new RuntimeException("自增序列号重置失败，序列类型不能为空");
        }
        seqVal = oConvertUtils.isEmpty(seqVal) ? "-" : seqVal;

        return mdmSequenceMapper.resetSeqNo(seqType, seqVal);
    }
}
